package org.jeecg.modules.lab.entrust.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.lab.entrust.entity.LabEntrustItems;
import org.jeecg.modules.lab.entrust.mapper.LabEntrustItemsMapper;
import org.jeecg.modules.lab.entrust.service.ILabEntrustItemsService;
import org.jeecg.modules.lab.items.vo.LabEntrustItemPage;
import org.jeecg.modules.lab.utensil.entity.MonthList;
import org.quartz.SimpleTrigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.DecimalFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Description: 实验项目表
 * @Author: jeecg-boot
 * @Date: 2023-08-10
 * @Version: V1.0
 */
@Service
public class LabEntrustItemsServiceImpl extends ServiceImpl<LabEntrustItemsMapper, LabEntrustItems> implements ILabEntrustItemsService {


    @Autowired
    private LabEntrustItemsMapper labEntrustItemsMapper;

    @Override
    public List<LabEntrustItems> selectItemsByMainId(String mainId) {
        return labEntrustItemsMapper.selectItemsByMainId(mainId);
    }

    /**
     * 首页个人工作量统计：
     * 待检项目数，当月检测数，当月实验时间，当月加班时间，累计检测数，累计实验时间
     * 统计图：每月实验数，每月实验时间
     *
     * @param id
     */
    @Override
    public Map<String, Object> countMessage(String id, String yearValue) {
        Map<String, Object> map = new HashMap<>();
        List<LabEntrustItems> labEntrustItems = labEntrustItemsMapper.selectList(new LambdaQueryWrapper<LabEntrustItems>().eq(LabEntrustItems::getUserId, id));
        int waitNum = 0;//待检项目数
        int monthNum = 0;//当月检测数
        int allNum = 0;//累计检测数
        Map<String, Object> mapNum = new HashMap<>();//每月检测项目数
        Map<String, Object> mapTime = new HashMap<>();//每月实验时间
        long overTime = 0l;//当月加班时间
        long totalTime = 0l;//累计实验时间
        long monthTime = 0l;//当月实验时间
        List<String> numMonth = new ArrayList<>();
        List<String> numValue = new ArrayList<>();
        List<MonthList> monthLists = labEntrustItemsMapper.numMonth(yearValue);
        monthLists.forEach(e -> {
            numMonth.add(e.getMonth() + "月");
            numValue.add(e.getCount());
        });
        mapNum.put("xAxis", numMonth);
        mapNum.put("yAxis", numValue);
        List<String> timeMonth = new ArrayList<>();
        List<String> timeValue = new ArrayList<>();
        List<MonthList> lists = labEntrustItemsMapper.timeMonth(yearValue);
        lists.forEach(e -> {
            timeMonth.add(e.getMonth() + "月");
            timeValue.add(e.getCount());
        });
        mapTime.put("xAxis", timeMonth);
        mapTime.put("yAxis", timeValue);

        for (int i = 0; i < labEntrustItems.size(); i++) {
            LabEntrustItems entrustItems = labEntrustItems.get(i);
            String itemStatus = entrustItems.getItemStatus();
            Date startTime =entrustItems.getItemStartTime();
            Date finishTime =entrustItems.getItemFinishTime();
            if ("待实验".equals(itemStatus)) {
                waitNum += 1;
            }
            if (finishTime != null) {
                String[] strings = finishTime.toString().split(" ");
                String[] nowString = new Date().toString().split(" ");
                if ("已实验".equals(itemStatus)) {
                    allNum += 1;
                    if (strings[5].equals(nowString[5]) && strings[1].equals(nowString[1])) {//比较判断年份和月份
                        //这是当前月
                        monthNum += 1;
                        if (startTime != null) {
                            monthTime += (finishTime.getTime() - startTime.getTime());
                        }
                    }
                }
            }
            if ("已实验".equals(itemStatus) || "待复核".equals(itemStatus)) {
                if (startTime != null && finishTime != null) {
                    totalTime += (finishTime.getTime() - startTime.getTime());//获取所有实验累计时间

                }
            }
        }
        //当月每日最后提交的实验
        List<LabEntrustItems> items = labEntrustItemsMapper.selectMaxDay(id);
//        LocalDateTime deadline = LocalDateTime.of(LocalDate.now(), LocalTime.of(17, 0)); // 当天晚上5点的时间
        for (int k = 0; k < items.size(); k++) {
            // 将输入日期字符串解析为 LocalDateTime 对象
            DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss zzz uuuu", Locale.ENGLISH);
            LocalDateTime dateTime = LocalDateTime.parse(items.get(k).getItemFinishTime().toString(), inputFormatter);
            // 格式化为指定格式的字符串
            DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedDate = dateTime.format(outputFormatter);

            LocalDateTime specifiedDateTime = LocalDateTime.parse(formattedDate.split(" ")[0] + " 17:00:00", outputFormatter);
            if (dateTime.isAfter(specifiedDateTime)) {
                // 计算两个时间戳之间的毫秒值差
                long millisDiff = Duration.between(specifiedDateTime.toInstant(ZoneOffset.UTC), dateTime.toInstant(ZoneOffset.UTC)).toMillis();
                overTime += millisDiff;
            }

        }
        //加班时间转为小时
        double hours = (double) overTime / (60 * 60 * 1000);
        DecimalFormat df = new DecimalFormat("#.#");
        String formattedHours = df.format(hours);
        //累计实验时间转为小时
        double hoursTotal = (double) totalTime / (60 * 60 * 1000);
        String total = df.format(hoursTotal);
        //当月实验时间转为小时
        double hoursMonth = (double) monthTime / (60 * 60 * 1000);
        String month = df.format(hoursMonth);
        map.put("waitNum", waitNum);
        map.put("monthNum", monthNum);
        map.put("monthTime", month);
        map.put("overTime", formattedHours);
        map.put("allNum", allNum);
        map.put("totalTime", total);
        map.put("mapNum", mapNum);
        map.put("mapTime", mapTime);
        return map;
    }

    @Override
    public Map<String, Object> countYear(String year) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapNum = new HashMap<>();//每月检测项目数
        Map<String, Object> mapTime = new HashMap<>();//每月实验时间
        List<String> numMonth = new ArrayList<>();
        List<String> numValue = new ArrayList<>();
        List<MonthList> monthLists = labEntrustItemsMapper.numMonth(year);
        monthLists.forEach(e -> {
            numMonth.add(e.getMonth() + "月");
            numValue.add(e.getCount());
        });
        mapNum.put("xAxis", numMonth);
        mapNum.put("yAxis", numValue);
        List<String> timeMonth = new ArrayList<>();
        List<String> timeValue = new ArrayList<>();
        List<MonthList> lists = labEntrustItemsMapper.timeMonth(year);
        lists.forEach(e -> {
            timeMonth.add(e.getMonth() + "月");
            timeValue.add(e.getCount());
        });
        mapTime.put("xAxis", timeMonth);
        mapTime.put("yAxis", timeValue);
        map.put("mapNum", mapNum);
        map.put("mapTime", mapTime);
        return map;
    }

    @Override
    public List<LabEntrustItemPage> getEntrustItemList(String kyId) {
        return labEntrustItemsMapper.getEntrustItemList(kyId);
    }

    @Override
    public List<LabEntrustItems> queryItemsList(String entrustId,String userId) {
        return labEntrustItemsMapper.getItemsList(entrustId,userId);
    }


}
